import {
  Body,
  Controller,
  Get,
  HttpException,
  Post,
  Req,
} from '@nestjs/common';
import { RVo } from '../utils/result.vo';
import { AuthService } from './auth.service';
import { Public } from './decorators/auth.decorator';
import { LoginByPhoneDto } from './dto/login.dto';
import { UpdatePhoneDto } from './dto/update-phone.dto';

@Controller('auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  // 通过手机验证码注册登录
  @Post('login/phone')
  @Public()
  async signInByWxappPhone(@Body() signInDto: LoginByPhoneDto) {
    const data = await this.authService.signInByPhone(signInDto);
    return new RVo({ data });
  }

  // 微信小程序登录
  @Post('login/wx/phone')
  @Public()
  async updatePhone(
    @Req() req: Request,
    @Body() updatePhoneDto: UpdatePhoneDto,
  ) {
    const headers = req.headers;
    const wxOpenID = headers['x-wx-openid'];
    if (!wxOpenID) {
      throw new HttpException('使用微信小程序提供的云托管调用', 400);
    }
    const data = await this.authService.updatePhone(updatePhoneDto, wxOpenID);
    return new RVo({ data });
  }

  // 微信小程序获取token
  @Get('wx/token')
  @Public()
  async signInByWxapp(@Req() req: Request) {
    const headers = req.headers;
    const wxOpenID = headers['x-wx-openid'];
    if (!wxOpenID) {
      throw new HttpException('使用微信小程序提供的云托管调用', 400);
    }
    const data = await this.authService.getTokenByWxapp(wxOpenID);
    return new RVo({ data });
  }
}
